/*
 * @Author: wuhao930406 1148547900@qq.com
 * @Date: 2023-09-13 13:54:09
 * @LastEditors: wuhao930406 1148547900@qq.com
 * @LastEditTime: 2023-10-18 14:24:29
 * @FilePath: /utools_web/src/components/Limit/index.jsx
 * @Description:
 *
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
 */
/* eslint-disable eqeqeq */
import { Image } from "antd";
import "braft-editor/dist/output.css";
import Prism from "prismjs";
import { useEffect, useRef, useState } from "react";
import "prismjs/themes/prism-tomorrow.min.css";

Prism.hooks.add("before-highlight", function (env) {
  env.element.innerHTML = env.element.innerHTML.replace(/<br\s*\/?>/g, "\n");
  env.code = env.element.textContent.replace(/^(?:\r?\n|\r)/, "");
});

function Limit({ content, style = {} }) {
  const [preview, setpreview] = useState({
    visible: false,
  });
  const containerRef = useRef();

  const handleClick = (e) => {
    if (e.target.tagName !== "IMG") {
      return;
    }
    let srcarr = [],
      current = 0;
    if (containerRef?.current) {
      const imgTags = containerRef.current.querySelectorAll("img");
      srcarr = Array.from(imgTags)?.map((el, i) => {
        if (el.src === e.target.src) {
          current = i + 1;
        }
        return el.src;
      });
    }
    setpreview((s) => ({
      current: current,
      urls: srcarr,
      visible: true,
    }));
  };
  useEffect(() => {
    Prism.highlightAll();
  }, []);

  return (
    <div style={style} className="braft-output-content">
      <div
        style={{
          display: "none",
        }}
      >
        <Image.PreviewGroup
          preview={{
            visible: preview?.visible,
            current: preview?.current - 1,
            onVisibleChange: (vis) =>
              setpreview((s) => ({
                ...s,
                visible: vis,
              })),
          }}
        >
          {preview?.urls?.map?.((it) => (
            <Image src={it} key={it} />
          ))}
        </Image.PreviewGroup>
      </div>
      <div
        onClick={handleClick}
        ref={containerRef}
        dangerouslySetInnerHTML={{ __html: content }}
        className="limit"
      ></div>
    </div>
  );
}

export default Limit;
